import { isValid, Node } from "cc";
import { AsyncScheduler } from "../../internal/scheduler/AsyncScheduler";
import { CreatorAction } from "./CreatorAction";

export class CreatorScheduler extends AsyncScheduler {

    public node: Node = null;
    public needValid: boolean = false; // 必须valid
    public needActive: boolean = false; // 必须active
    public needCache: boolean = false; // 需要缓存

    public actions: Array<CreatorAction<any>> = [];

    public flush(action: CreatorAction<any>): void {
        const { actions } = this;

        if (this._active) {
            actions.push(action);
            return;
        }

        // 根据node状态
        let passed = true;
        if (this.needValid && !isValid(this.node)) {
            passed = false;
        }
        if (this.needActive && isValid(this.node) && !this.node.active) {
            passed = false;
        }
        if (!passed) {
            if (this.needCache) actions.push(action);
            return;
        }

        let error: any;
        this._active = true;

        do {
            if ((error = action.execute(action.state, action.delay))) {
                break;
            }
        } while ((action = actions.shift()!)); // exhaust the scheduler queue

        this._active = false;

        if (error) {
            while ((action = actions.shift()!)) {
                action.unsubscribe();
            }
            throw error;
        }
    }
}